<template>
  <div class="product-detail-container" v-loading="loading">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/userWeb/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item v-if="product.categoryId" 
          :to="{ path: `/userWeb/category/${product.categoryId}` }">
          {{ getCategoryName(product.categoryId) }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 商品基本信息 -->
    <div class="product-main" v-if="product.id">
      <div class="product-gallery">
        <div class="main-image">
          <el-image 
            :src="product.cover || defaultImage" 
            fit="contain"
            :preview-src-list="productImages"
          />
        </div>
        <div class="image-thumbnails" v-if="productImages.length > 1">
          <div 
            v-for="(img, index) in productImages" 
            :key="index"
            class="thumbnail"
            :class="{ active: currentImageIndex === index }"
            @click="currentImageIndex = index"
          >
            <el-image :src="img" fit="cover" />
          </div>
        </div>
      </div>

      <div class="product-info">
        <h1 class="product-title">{{ product.title }}</h1>
        
        <div class="product-meta">
          <div class="product-id">商品编号：{{ product.id }}</div>
          <div class="product-sales">销量：{{ product.sales }}</div>
        </div>

        <div class="product-price">
          <div class="current-price">
            <span class="price-label">价格：</span>
            <span class="price-value">¥{{ selectedSpec ? selectedSpec.price : product.price }}</span>
          </div>
          <div class="original-price" v-if="product.originPrice">
            <span class="price-label">原价：</span>
            <span class="price-value">¥{{ product.originPrice }}</span>
          </div>
        </div>

        <!-- 商品规格 -->
        <div class="product-specs" v-if="productSpecs.length > 0">
          <div class="spec-group">
            <div class="spec-title">规格选择：</div>
            <div class="spec-options">
              <el-radio-group v-model="selectedSpecId">
                <el-radio 
                  v-for="spec in productSpecs" 
                  :key="spec.id" 
                  :label="spec.id"
                  :disabled="spec.stock <= 0"
                >
                  {{ spec.name }} 
                  <span class="spec-price">(¥{{ spec.price }})</span>
                  <span class="spec-stock" :class="{ 'no-stock': spec.stock <= 0 }">
                    {{ spec.stock > 0 ? `库存: ${spec.stock}` : '无货' }}
                  </span>
                </el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>

        <!-- 购买数量 -->
        <div class="product-quantity" v-if="maxStock > 0">
          <span class="quantity-label">购买数量：</span>
          <el-input-number 
            v-model="quantity" 
            :min="1" 
            :max="maxStock"
            size="large"
          />
          <span class="stock-info">库存：{{ maxStock }}</span>
        </div>
        <div class="no-stock-tip" v-else>
          <el-alert
            title="商品暂时无货"
            type="warning"
            :closable="false"
          />
        </div>

        <!-- 购买按钮 -->
        <div class="product-actions">
          <el-button 
            type="primary" 
            size="large" 
            :disabled="!canAddToCart"
            @click="addToCart"
            :loading="addingToCart"
          >
            <el-icon><ShoppingCart /></el-icon> 加入购物车
          </el-button>
          <el-button 
            type="danger" 
            size="large" 
            :disabled="!canAddToCart"
            @click="buyNow"
          >
            立即购买
          </el-button>
        </div>

        <!-- 商品服务 -->
        <div class="product-services">
          <div class="service-item">
            <el-icon><Check /></el-icon>
            <span>正品保障</span>
          </div>
          <div class="service-item">
            <el-icon><Check /></el-icon>
            <span>极速配送</span>
          </div>
          <div class="service-item">
            <el-icon><Check /></el-icon>
            <span>7天无理由退换</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情 -->
    <div class="product-details" v-if="product.id">
      <el-tabs>
        <el-tab-pane label="商品详情">
          <div class="detail-content" v-html="product.description || '暂无详细描述'"></div>
        </el-tab-pane>
        <el-tab-pane label="规格参数">
          <div class="specs-content">
            <el-descriptions :column="1" border>
              <el-descriptions-item v-for="(value, key) in product.specs" :key="key" :label="key">
                {{ value }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 相关推荐 -->
    <div class="related-products" v-if="relatedProducts.length > 0">
      <h2 class="section-title">相关推荐</h2>
      <div class="product-list">
        <div v-for="item in relatedProducts" :key="item.id" class="product-item">
          <div class="product-card" @click="goToProductDetail(item.id)">
            <div class="product-img">
              <el-image :src="getImageUrl(item)" fit="cover" />
            </div>
            <div class="product-info">
              <div class="product-title">{{ item.title }}</div>
              <div class="product-price">¥{{ item.price }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品不存在 -->
    <el-empty v-if="!loading && !product.id" description="商品不存在或已下架"></el-empty>
  </div>
</template>

<script>
export default {
  name: 'UserWebProduct'
}
</script>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ShoppingCart, Check } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const product = ref({});
const productSpecs = ref([]);
const selectedSpecId = ref(null);
const quantity = ref(1);
const addingToCart = ref(false);
const currentImageIndex = ref(0);
const defaultImage = ''; // 内联Base64编码的默认图片
const relatedProducts = ref([]);
const baseUrl = 'http://localhost:9191'; // 后端服务器基础URL

// 商品图片列表
const productImages = computed(() => {
  const images = [];
  
  // 添加主图
  if (product.value.cover) {
    images.push(product.value.cover);
  }
  
  // 添加其他图片
  if (product.value.images && Array.isArray(product.value.images)) {
    images.push(...product.value.images);
  }
  
  // 如果没有图片，使用默认图片
  if (images.length === 0) {
    images.push(defaultImage);
  }
  
  return images;
});

// 当前选中的规格
const selectedSpec = computed(() => {
  return productSpecs.value.find(spec => spec.id === selectedSpecId.value);
});

// 最大可购买数量
const maxStock = computed(() => {
  // 如果选择了规格，返回该规格库存
  if (selectedSpec.value) {
    return selectedSpec.value.stock;
  }
  // 否则返回商品总库存
  return product.value.stock || 0;
});

// 是否可以加入购物车
const canAddToCart = computed(() => {
  // 没有规格时，直接检查库存
  if (productSpecs.value.length === 0) {
    return (product.value.stock || 0) > 0;
  }
  
  // 有规格但未选择时，不能加入购物车
  if (!selectedSpecId.value) {
    return false;
  }
  
  // 选择了规格，检查该规格库存
  return maxStock.value > 0;
});

// 拼接图片URL
const getImageUrl = (item) => { 
  // 检查图片路径
  let imgPath = item.img || item.picture || item.imgUrl || item.cover || item.imgs;
  
  // 如果路径以http或https开头，说明是完整的URL，直接返回
  if (imgPath && (imgPath.startsWith('http://') || imgPath.startsWith('https://'))) {
    return imgPath;
  }
  
  // 如果路径以/file/开头，需要拼接后端服务器地址
  if (imgPath && imgPath.startsWith('/file/')) {
    return `${baseUrl}${imgPath}`;
  }
  
  // 其他情况直接拼接
  if (imgPath) {
    return `${baseUrl}/file/${imgPath}`;
  }

  // 默认图片
  return defaultImage;
};

// 获取商品详情
const fetchProductDetail = async (id) => {
  loading.value = true;
  try {
    // 获取商品详情
    const response = await request.get(`/api/good/${id}`);
    if (response && response.code === '200') {
      const data = response.data || {};
      console.log('商品原始数据:', data);
      
      // 处理商品数据
      product.value = {
        id: data.id,
        title: data.name || data.title || '未命名商品',
        description: data.description || '',
        price: data.price || data.specPrice || 0,
        originPrice: data.originPrice,
        sales: data.sales || 0,
        stock: 0,  // 默认设置为0，稍后从规格中获取总库存
        categoryId: data.categoryId,
        cover: null
      };
      
      // 处理图片
      if (data.imgs) {
        let imgUrl = data.imgs;
        // 如果路径以http或https开头，说明是完整的URL，直接使用
        if (imgUrl && (imgUrl.startsWith('http://') || imgUrl.startsWith('https://'))) {
          product.value.cover = imgUrl;
        }
        // 如果路径以/file/开头，需要拼接后端服务器地址
        else if (imgUrl && imgUrl.startsWith('/file/')) {
          product.value.cover = baseUrl + imgUrl;
        }
        // 其他情况直接拼接
        else if (imgUrl) {
          product.value.cover = `${baseUrl}/file/${imgUrl}`;
        }
      }
      
      // 获取商品规格
      await fetchProductSpecs(id);
      
      // 如果有规格，从规格中计算总库存
      if (productSpecs.value.length > 0) {
        product.value.stock = productSpecs.value.reduce((total, spec) => total + spec.stock, 0);
      }
      
      console.log('处理后的商品数据:', product.value);
      
      // 获取相关推荐
      fetchRelatedProducts(product.value.categoryId);
      
      // 设置页面标题
      document.title = product.value.title ? `${product.value.title} - 在线商城` : '商品详情 - 在线商城';
    } else {
      product.value = {};
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    product.value = {};
  } finally {
    loading.value = false;
  }
};

// 获取商品规格
const fetchProductSpecs = async (id) => {
  try {
    // 获取规格信息
    const response = await request.get(`/api/good/standard/${id}`);
    if (response && response.code === '200') {
      // 解析规格数据，将字符串解析为JSON对象
      let specData;
      try {
        // 如果返回的已经是数组，直接使用；如果是JSON字符串，需要解析
        if (typeof response.data === 'string') {
          specData = JSON.parse(response.data);
        } else {
          specData = response.data || [];
        }
        
        // 确保specData是一个数组
        if (!Array.isArray(specData)) {
          specData = specData ? [specData] : [];
        }
        
        console.log('规格数据:', specData);

        // 处理规格数据，添加id字段，并确保字段名称正确
        productSpecs.value = specData.map((spec, index) => ({
          id: index + 1,
          name: spec.value || `规格${index + 1}`,
          price: spec.price || 0,
          stock: spec.store || 0  // 注意：后端返回的是store字段，前端使用stock
        }));
        
        console.log('处理后的规格:', productSpecs.value);
        
        // 如果有规格，默认选择第一个有库存的规格
        if (productSpecs.value.length > 0) {
          const availableSpec = productSpecs.value.find(spec => spec.stock > 0);
          if (availableSpec) {
            selectedSpecId.value = availableSpec.id;
          } else {
            selectedSpecId.value = productSpecs.value[0].id;
          }
        }
      } catch (e) {
        console.error('解析商品规格数据失败:', e);
        productSpecs.value = [];
      }
    } else {
      productSpecs.value = [];
    }
  } catch (error) {
    console.error('获取商品规格失败:', error);
    productSpecs.value = [];
  }
};

// 获取相关推荐
const fetchRelatedProducts = async (categoryId) => {
  if (!categoryId) return;
  
  try {
    // 根据分类ID获取相关商品
    const response = await request.get(`/api/good`, {
      params: {
        categoryId: categoryId,
        pageNum: 1,
        pageSize: 4
      }
    });
    
    if (response && response.code === '200' && response.data) {
      // 映射数据，确保字段名称正确
      const products = (response.data.records || []).map(item => ({
        id: item.id,
        title: item.name || item.title || '未命名商品',
        imgs: item.imgs || item.cover || item.img || item.picture,
        price: item.price || item.specPrice || 0
      }));
      
      // 过滤掉当前正在查看的商品
      relatedProducts.value = products.filter(p => p.id !== product.value.id).slice(0, 4);
      
      console.log('相关推荐商品:', relatedProducts.value);
    } else {
      // 如果API调用失败或没有数据，使用模拟数据
      useDefaultRelatedProducts();
    }
  } catch (error) {
    console.error('获取相关商品失败:', error);
    // 使用默认数据
    useDefaultRelatedProducts();
  }
};

// 使用默认的相关推荐数据
const useDefaultRelatedProducts = () => {
  relatedProducts.value = Array(4).fill().map((_, index) => ({
    id: 100 + index,
    title: `相关商品 ${index + 1}`,
    imgs: defaultImage,
    price: Math.floor(Math.random() * 9000) + 1000
  }));
};

// 获取分类名称
const getCategoryName = (categoryId) => {
  const categories = {
    1: '手机数码',
    2: '电脑办公',
    3: '家用电器',
    4: '服装鞋包',
    5: '美妆个护'
  };
  return categories[categoryId] || '全部商品';
};

// 跳转到其他商品详情
const goToProductDetail = (id) => {
  router.push(`/userWeb/product/${id}`);
};

// 加入购物车
const addToCart = async () => {
  // 检查用户是否登录
  const userStr = sessionStorage.getItem('user');
  if (!userStr) {
    ElMessageBox.confirm('您尚未登录，是否前往登录页面？', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push({
        path: '/login',
        query: { redirect: route.fullPath }
      });
    }).catch(() => {});
    return;
  }

  // 如果有规格但未选择规格
  if (productSpecs.value.length > 0 && !selectedSpecId.value) {
    ElMessage.warning('请选择商品规格');
    return;
  }
  
  addingToCart.value = true;
  try {
    // 获取选中的规格信息
    const selectedSpec = productSpecs.value.find(spec => spec.id === selectedSpecId.value);
    
    // 构建购物车数据
    const cartData = {
      userId: JSON.parse(userStr).id,
      goodId: product.value.id,
      standardId: selectedSpec ? selectedSpec.id : null,
      standard: selectedSpec ? selectedSpec.name : '',
      count: quantity.value,
      // price: selectedSpec ? selectedSpec.price : product.value.price,
      // goodName: product.value.title,
      // goodImg: product.value.cover,
      createTime: new Date().toLocaleString()
    };
    
    // 调用后端接口添加到购物车
    const response = await request.post(`/api/cart`, cartData);
    
    if (response && response.code === '200') {
      ElMessage.success('成功加入购物车');
    } else {
      ElMessage.error(response.msg || '加入购物车失败');
    }
  } catch (error) {
    console.error('加入购物车失败:', error);
    ElMessage.error('加入购物车失败，请稍后再试');
  } finally {
    addingToCart.value = false;
  }
};

// 立即购买
const buyNow = () => {
  // 检查用户是否登录
  const userStr = sessionStorage.getItem('user');
  if (!userStr) {
    ElMessageBox.confirm('您尚未登录，是否前往登录页面？', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push({
        path: '/login',
        query: { redirect: route.fullPath }
      });
    }).catch(() => {});
    return;
  }
  
  // 立即购买逻辑
  addToCart();
  router.push('/userWeb/cart');
};

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchProductDetail(newId);
  }
}, { immediate: true });

onMounted(() => {
  if (route.params.id) {
    fetchProductDetail(route.params.id);
  }
});
</script>

<style scoped>
.product-detail-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.breadcrumb-nav {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

/* 商品主区域 */
.product-main {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  margin-bottom: 30px;
}

.product-gallery {
  flex: 0 0 450px;
}

.product-info {
  flex: 1;
  min-width: 300px;
}

.main-image {
  width: 100%;
  height: 450px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #f0f0f0;
  margin-bottom: 10px;
}

.main-image .el-image {
  width: 100%;
  height: 100%;
}

.image-thumbnails {
  display: flex;
  gap: 10px;
  padding: 10px 0;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  cursor: pointer;
  transition: all 0.3s;
}

.thumbnail.active {
  border-color: #409EFF;
}

.thumbnail .el-image {
  width: 100%;
  height: 100%;
}

/* 商品信息 */
.product-title {
  font-size: 24px;
  margin: 0 0 15px;
  color: #333;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

.product-price {
  background-color: #f9f9f9;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.current-price {
  font-size: 18px;
  margin-bottom: 10px;
}

.current-price .price-value {
  color: #ff4d4f;
  font-size: 26px;
  font-weight: bold;
}

.original-price .price-value {
  text-decoration: line-through;
  color: #999;
}

/* 规格选择 */
.product-specs {
  margin-bottom: 20px;
}

.spec-group {
  margin-bottom: 15px;
}

.spec-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.spec-options {
  margin-left: 10px;
}

/* 数量选择 */
.product-quantity {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.quantity-label {
  margin-right: 15px;
}

.stock-info {
  margin-left: 15px;
  color: #999;
  font-size: 14px;
}

/* 购买按钮 */
.product-actions {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.product-actions .el-button {
  padding: 12px 25px;
  font-size: 16px;
}

/* 商品服务 */
.product-services {
  border-top: 1px solid #eee;
  padding-top: 20px;
  display: flex;
  gap: 30px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.service-item .el-icon {
  color: #52c41a;
}

/* 商品详情 */
.product-details {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.detail-content {
  padding: 20px 0;
  line-height: 1.8;
}

/* 相关推荐 */
.related-products {
  margin-top: 40px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.section-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.product-card {
  cursor: pointer;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s;
  border: 1px solid #eee;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.product-card .product-img {
  height: 200px;
  overflow: hidden;
}

.product-card .product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-img img {
  transform: scale(1.05);
}

.product-card .product-info {
  padding: 10px;
}

.product-card .product-title {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-card .product-price {
  color: #ff4d4f;
  font-weight: bold;
  background: none;
  padding: 0;
  margin: 0;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .product-main {
    flex-direction: column;
  }
  
  .product-gallery {
    flex: 0 0 auto;
    width: 100%;
  }
}

.spec-price {
  color: #ff4d4f;
  margin-left: 5px;
  font-size: 13px;
}

.spec-stock {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 5px;
  border-radius: 3px;
}

.spec-stock.no-stock {
  color: #ff4d4f;
  background-color: #fff1f0;
}

.no-stock-tip {
  margin: 15px 0;
}

.el-radio {
  margin-bottom: 10px;
  display: block;
}
</style> 